﻿/* 
 * Since 2008 - 2012
 */

package com.hh.bss.customer.service.impl;

import org.apache.commons.lang3.StringUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

import com.hh.bss.auth.client.OnlineUser;
import com.hh.bss.auth.entity.SystemBranchDept;
import com.hh.bss.auth.entity.SystemBranchTitle;
import com.hh.bss.auth.entity.SystemUserTitle;
import com.hh.bss.base.*;
import com.hh.bss.common.MapObjectRowMapper;
import com.hh.bss.common.cache.CustomerCache;
import com.hh.bss.common.exception.RepeatRecordException;
import com.hh.bss.common.page.*;
import com.hh.bss.common.page.impl.*;
import com.hh.bss.common.tree.CompanyCvTreeNode;
import com.hh.bss.common.tree.CompanyDeptTitleTreeNode;
import com.hh.bss.common.tree.CompanyDeptTreeNode;
import com.hh.bss.common.tree.TreeNode;
import com.hh.bss.customer.dao.*;
import com.hh.bss.customer.entity.*;
import com.hh.bss.customer.service.*;
import com.hh.bss.customer.vo.query.*;
import com.hh.bss.project.entity.SearchProjectCv;
import com.hh.bss.talent.dao.CvDao;
import com.hh.bss.talent.entity.Cv;
import com.hh.bss.talent.entity.CvSimple;
import com.hh.bss.util.*;



@Service
@Transactional
public class CompanyServiceImpl extends BaseBusinessService<Company, java.lang.Integer> implements CompanyService<Company, java.lang.Integer> {

	private CompanyDao companyDao;
	private CompanyCvDao companyCvDao;
	private CvDao cvDao;

	/** 增加setXXXX()方法,spring就可以通过autowire自动设置对象属性,请注意大小写 */
	public void setCompanyDaoImpl(CompanyDao dao) {
		this.companyDao = dao;
	}

	public void setCompanyCvDaoImpl(CompanyCvDao dao) {
		this.companyCvDao = dao;
	}

	public void setCvDaoImpl(CvDao dao) {
		this.cvDao = dao;
	}

	public EntityDao getEntityDao() {
		return this.companyDao;
	}

	@Override
	public void update(Company entity) throws DataAccessException {
		companyDao.update(entity);
		//更新人才仓库公司名字
		cvDao.updateCompanyName(entity.getId(),entity.getAbbrName());
	}
	
	public Page findSimplePage(CompanyQuery query) {

		Page page = companyDao.findSimplePage(query);
		return page;
	}

	@Transactional(readOnly = true)
	public Page findPage(CompanyQuery query) {

		Page page = companyDao.findPage(query);

		List companyList = (List) page.getResult();
		// 设置cc项目名
		Map m = null;
		for (int i = 0; companyList != null && i < companyList.size(); i++) {
			m = (Map) companyList.get(i);
			// Integer companyId = ;
			String person = this.companyCvDao.getManagerByCompanyId((Integer) m.get("id"));
			m.put("person", person);// 负责人
			if (CustomerCache.isCustomerBDByCompanyId((Integer) m.get("id"))) {
				m.put("custId", "1");
			} else {
				m.put("custId", null);
			}

			if (CustomerCache.isCustomerByCompanyId((Integer) m.get("id"))) {
				m.put("contractId", "1");
			} else {
				m.put("contractId", null); // 客户经理
			}

		}

		return page;

		// return companyDao.findPage(query);
	}

	public boolean isLvCv(Integer id) {
		// TODO Auto-generated method stub

		List l = companyDao.findcv(id);
		if (l != null & l.size() > 0)
			return true;

		return false;
	}

	public List getOrg(Integer companyId, Integer deptId) {
		return getOrg(companyId, deptId, true);
	}

	private List getOrg(Integer companyId, Integer deptId, boolean hasCv) {
		// TODO Auto-generated method stub
		// 查询所有的部门
		Object[] os = { companyId };
		
		List allDeptList = this.getEntityDao().getHibernateTemplate().find("from CompanyDept a where a.companyId=? order by  convert(a.name) ", os);
		Map allDeptTreeNodeMap = new LinkedHashMap();
		// allDeptMap.keySet().
		CompanyDept companyDept = null;
		CompanyDeptTreeNode companyDeptTreeNode = null;
		for (int i = 0; allDeptList != null && i < allDeptList.size(); i++) {

			companyDept = (CompanyDept) allDeptList.get(i);
			companyDeptTreeNode = new CompanyDeptTreeNode();
			companyDeptTreeNode.setParentId(ObjectUtils.toString(companyDept.getParentId()));
			companyDeptTreeNode.setText(companyDept.getName());
			companyDeptTreeNode.setId(ObjectUtils.toString(companyDept.getCompanyId()) + companyDept.getId().toString());
			companyDeptTreeNode.setDeptId(companyDept.getId().toString());
			companyDeptTreeNode.setCompanyId(ObjectUtils.toString(companyDept.getCompanyId()));

			allDeptTreeNodeMap.put(companyDept.getId(), companyDeptTreeNode);
		}

		// 设置 子部门
		CompanyDept childDept = null;
		CompanyDeptTreeNode parentNode = null;
		CompanyDeptTreeNode childNode = null;
		for (int i = 0; allDeptList != null && i < allDeptList.size(); i++) {
			childDept = (CompanyDept) allDeptList.get(i);
			parentNode = (CompanyDeptTreeNode) allDeptTreeNodeMap.get(childDept.getParentId());
			childNode = (CompanyDeptTreeNode) allDeptTreeNodeMap.get(childDept.getId());
			if (parentNode != null && childNode != null)
				parentNode.addChildren(childNode);
		}

		// 查询所有的职位
		List allTitletList = this.getEntityDao().getHibernateTemplate().find("from CompanyDeptTitle dt where dt.companyId=? order by dt.name ", os);

		Map allTitleTreeNodeMap = new LinkedHashMap();
		CompanyDeptTitle companyDeptTitle = null;
		CompanyDeptTreeNode one = null;
		CompanyDeptTitleTreeNode companyDeptTitleTreeNode = null;
		for (int i = 0; allTitletList != null && i < allTitletList.size(); i++) {

			companyDeptTitle = (CompanyDeptTitle) allTitletList.get(i);
			// 在岗位节点上设置部门名称
			parentNode = (CompanyDeptTreeNode) allDeptTreeNodeMap.get(companyDeptTitle.getDeptId());
			companyDeptTitleTreeNode = new CompanyDeptTitleTreeNode();
			companyDeptTitleTreeNode.setParentId(ObjectUtils.toString(companyDeptTitle.getParentId()));
			if (parentNode != null)
				companyDeptTitleTreeNode.setDeptName(parentNode.getText());
			companyDeptTitleTreeNode.setText(companyDeptTitle.getName());
			companyDeptTitleTreeNode.setCompanyId(ObjectUtils.toString(companyDeptTitle.getCompanyId()));
			companyDeptTitleTreeNode.setTitleId(companyDeptTitle.getId().toString());
			companyDeptTitleTreeNode.setDeptId(ObjectUtils.toString(companyDeptTitle.getDeptId()));
			companyDeptTitleTreeNode.setId(ObjectUtils.toString(companyDeptTitle.getDeptId()) + ObjectUtils.toString(companyDeptTitle.getDeptId()) + companyDeptTitle.getId().toString());
			// 将岗位设置到部门,只有没有父 岗位才会设置，有父岗位的子岗位设置到父岗位下
			one = (CompanyDeptTreeNode) allDeptTreeNodeMap.get(companyDeptTitle.getDeptId());
			if (one != null && (companyDeptTitle.getParentId() == null || companyDeptTitle.getParentId().intValue() == 0))
				one.addChildren(companyDeptTitleTreeNode);

			allTitleTreeNodeMap.put(companyDeptTitle.getId(), companyDeptTitleTreeNode);

		}
		TreeNode oneTreeNode = null;
		if (hasCv) {
			// 查询所有的人才
			// List
			// allCvList=this.getEntityDao().getHibernateTemplate().find("select distinct c.companyId,c.deptId,c.titleId,c.cvId from SearchProjectCv c where c.companyId=? ",
			// os);
			// List
			// allCvList=this.getEntityDao().getHibernateTemplate().find("select distinct c.companyId,c.deptId,c.titleId,c.cvId,c.id from CompanyCv c where c.companyId=? ",
			// os);
			List values = new ArrayList();
			values.add(companyId);
			StringBuffer sql = new StringBuffer();
			sql.append("select info.* from (select a.company_id companyId,a.dept_id deptId,a.title_id titleId,a.cv_id cvId,a.id  from company_cv a,cv b where a.cv_id=b.id and b.is_delete=0 and a.company_id=?) info");
			List allCvList = this.getEntityDao().getJdbcDao().findByQuery(sql.toString(), values.toArray(), new MapObjectRowMapper());
			// this.
			// select * from search_project_cv a,cv b where a.cv_id=b.id

			SearchProjectCv searchProjectCv = null;
			CompanyCvTreeNode companyCvTreeNode = null;

			for (int j = 0; allCvList != null && j < allCvList.size(); j++) {

				// Object[] objects=(Object[])allCvList.get(j);
				Map objects = (Map) allCvList.get(j);
				Integer companyCvId = null;
				searchProjectCv = new SearchProjectCv();
				/*
				 * searchProjectCv.setCompanyId((Integer)objects[0]);
				 * searchProjectCv.setDeptId((Integer)objects[1]);
				 * searchProjectCv.setTitleId((Integer)objects[2]);
				 * searchProjectCv.setCvId((Integer)objects[3]); if
				 * (objects.length>3) companyCvId=(Integer)objects[4];
				 */
				searchProjectCv.setCompanyId((Integer) objects.get("companyId"));
				searchProjectCv.setDeptId((Integer) objects.get("deptId"));
				searchProjectCv.setTitleId((Integer) objects.get("titleId"));
				searchProjectCv.setCvId((Integer) objects.get("cvId"));
				companyCvId = (Integer) objects.get("id");

				companyCvTreeNode = new CompanyCvTreeNode();
				// companyTreeNode.setParentId(ObjectUtils.toString(companyDeptTitle.getParentId()));

				companyCvTreeNode.setCompanyId(ObjectUtils.toString(searchProjectCv.getCompanyId()));

				// if(companyCv.getCvSimple()!=null)companyCvTreeNode.setCvName(companyCv.getCvSimple().getCvName());
				CvSimple cvSimple = this.getEntityDao().getHibernateTemplate().get(CvSimple.class, searchProjectCv.getCvId());
				String lvTag = "";
				if (cvSimple != null) {
					companyCvTreeNode.setCvName(cvSimple.getCvName());

					if (this.isLvCv(cvSimple.getId()))
						lvTag = "(有简历)";
					if (cvSimple.getCompanyId() != null && cvSimple.getCompanyId().intValue() != 0 && cvSimple.getCompanyId().intValue() != companyId.intValue()) {

						if (StringHelper.isEmpty(lvTag))
							lvTag = "(离职)";
						else
							lvTag = "(有简历,离职)";
					}
				}
				// if (companyService.isLvCv(cvSimple.getId())) lvTag="(有简历)"

				companyCvTreeNode.setText(ObjectUtils.toString(companyCvTreeNode.getCvName()) + lvTag);
				companyCvTreeNode.setLeaf(true);
				companyCvTreeNode.setCompanyCvId(ObjectUtils.toString(companyCvId));
				companyCvTreeNode.setCvId(ObjectUtils.toString(searchProjectCv.getCvId()));
				companyCvTreeNode.setDeptId(ObjectUtils.toString(searchProjectCv.getDeptId()));
				companyCvTreeNode.setTitleId(ObjectUtils.toString(searchProjectCv.getTitleId()));
				// companyCvTreeNode.setCompanyCvId(searchProjectCv.getId().toString());
				companyCvTreeNode.setId(ObjectUtils.toString(searchProjectCv.getCvId()) + ObjectUtils.toString(searchProjectCv.getCompanyId()) + ObjectUtils.toString(searchProjectCv.getDeptId()) + ObjectUtils.toString(searchProjectCv.getTitleId()));
				oneTreeNode = (TreeNode) allTitleTreeNodeMap.get(searchProjectCv.getTitleId());
				if (oneTreeNode != null)
					oneTreeNode.addChildren(companyCvTreeNode);
				// allCvTreeNodMap.put(companyCv.getId(), companyTreeNode);
				// 设置人才到岗位里
				// childNode=(CompanyTreeNode)allTitleTreeNodMap.get(childTitle.getId());
			}
		}

		// 设置 子岗位
		CompanyDeptTitleTreeNode parentTitleNode = null;
		CompanyDeptTitleTreeNode childTitleNode = null;
		CompanyDeptTitle childTitle = null;
		for (int i = 0; allTitletList != null && i < allTitletList.size(); i++) {
			childTitle = (CompanyDeptTitle) allTitletList.get(i);
			parentTitleNode = (CompanyDeptTitleTreeNode) allTitleTreeNodeMap.get(childTitle.getParentId());
			childTitleNode = (CompanyDeptTitleTreeNode) allTitleTreeNodeMap.get(childTitle.getId());
			if (parentTitleNode != null && childTitleNode != null)
				parentTitleNode.addChildren(childTitleNode);
		}

		List nodeLists = new ArrayList();

		if (deptId == null || deptId.intValue() == 0) {
			// 只取parentId=0,根部门
			for (Iterator it = allDeptTreeNodeMap.values().iterator(); it.hasNext();) {
				CompanyDeptTreeNode oneDept = (CompanyDeptTreeNode) it.next();
				if (StringHelper.isEmpty(oneDept.getParentId()) || "0".equals(oneDept.getParentId()))
					nodeLists.add(oneDept);
			}
			// nodeLists.addAll(allDeptTreeNodeMap.values());
		} else {

			oneTreeNode = (TreeNode) allDeptTreeNodeMap.get(deptId);
			if (oneTreeNode != null)
				nodeLists.add(oneTreeNode);
		}
		
		return nodeLists;
	}

	private void traverseTree(CompanyCvTreeNode parentNode, List child, Map deptMap, Map titleMap, Map cvMap) {
		CompanyCvTreeNode companyCvTreeNode = null;
		for (int i = 0; child != null && i < child.size(); i++) {

			if (!(child.get(i) instanceof CompanyCvTreeNode)) {
				System.out.println("异常数据：" + i + "  " + child.get(i).getClass().getName());
				System.out.println("异常数据：" + i);
				continue;
			}

			companyCvTreeNode = (CompanyCvTreeNode) child.get(i);
			System.out.println(companyCvTreeNode.getCompanyNodeType() + "-company-" + companyCvTreeNode.getCompanyId() + "-dept-" + companyCvTreeNode.getDeptId() + "-title-" + companyCvTreeNode.getTitleId() + "-child data:" + child.get(i));

			if ("DEPT".equals(companyCvTreeNode.getCompanyNodeType())) {
				// 如果子节点是部门，则更新部门的上级部门和所属公司
				companyCvTreeNode.setCompanyId(parentNode.getCompanyId());

				if ("COMPANY".equals(parentNode.getCompanyNodeType())) {
					companyCvTreeNode.setParentId("0");
					companyCvTreeNode.setParentIds("/" + companyCvTreeNode.getDeptId() + "/");
				} else {
					companyCvTreeNode.setParentId(parentNode.getDeptId());
					companyCvTreeNode.setParentIds(parentNode.getParentIds() + companyCvTreeNode.getDeptId() + "/");
				}
				deptMap.put(companyCvTreeNode.getDeptId(), companyCvTreeNode);

			} else if ("TITLE".equals(companyCvTreeNode.getCompanyNodeType())) {
				// 如果子节点是岗位，则更新岗位的上级和所属部门
				companyCvTreeNode.setDeptId(parentNode.getDeptId());
				companyCvTreeNode.setCompanyId(parentNode.getCompanyId());

				if ("DEPT".equals(parentNode.getCompanyNodeType())) {
					companyCvTreeNode.setParentIds("/" + companyCvTreeNode.getTitleId() + "/");
					companyCvTreeNode.setParentId("0");
				} else {
					companyCvTreeNode.setParentId(parentNode.getTitleId());
					companyCvTreeNode.setParentIds(parentNode.getParentIds() + companyCvTreeNode.getTitleId() + "/");
				}
				titleMap.put(companyCvTreeNode.getTitleId(), companyCvTreeNode);

			} else if ("CV".equals(companyCvTreeNode.getCompanyNodeType())) {
				// 如果子节点是人员，则更新所属岗位
				companyCvTreeNode.setDeptId(parentNode.getDeptId());
				companyCvTreeNode.setCompanyId(parentNode.getCompanyId());
				companyCvTreeNode.setTitleId(parentNode.getTitleId());

				List l = (List) cvMap.get(companyCvTreeNode.getCvId());
				if (l == null) {
					l = new ArrayList();
					cvMap.put(companyCvTreeNode.getCvId(), l);
				}
				l.add(companyCvTreeNode);

			}

			// 子节点
			traverseTree(companyCvTreeNode, companyCvTreeNode.getChildren(), deptMap, titleMap, cvMap);

		}
	}

	public void saveOrgTree(OnlineUser onlineUser, Integer companyId, CompanyCvTreeNode root) {
		// TODO Auto-generated method stub

		// 根节点--分公司--部门-岗位-个人
		// CompanyCvTreeNode root=null;
		// Integer companyId=StringHelper.parseInteger(root.getCompanyId(), 0);
		if (root != null) {
			// root=(CompanyCvTreeNode)tree.get(0);
			// root=

			// 取部门id-Object
			// 取岗位id-Object
			// 取个人 id-List

			Map deptMap = new HashMap();
			Map titleMap = new HashMap();
			Map cvMap = new HashMap();

			List values = new ArrayList();

			traverseTree(root, root.getChildren(), deptMap, titleMap, cvMap);

			// 分公司不用处理
			// 处理部门
			CompanyDept companyDept = null;
			CompanyCvTreeNode one = null;
			for (Iterator it = deptMap.keySet().iterator(); it.hasNext();) {
				String deptId = (String) it.next();
				one = (CompanyCvTreeNode) deptMap.get(deptId);
				try {
					companyDept = this.getEntityDao().getHibernateTemplate().get(CompanyDept.class, StringHelper.parseInteger(deptId, 0));
					System.out.println("部门id:" + companyDept.getId() + " 公司id:" + one.getCompanyId() + " 上级id:" + one.getParentId());

					// 如果改变，则更新
					if (!StringHelper.parseInteger(one.getParentId(), 0).equals(companyDept.getParentId())) {

						// companyDept.setCompanyId(StringHelper.parseInteger(one.getCompanyId(),
						// 0));
						companyDept.setParentId(StringHelper.parseInteger(one.getParentId(), 0));
						companyDept.setModifiedDt(new Date());
						this.getEntityDao().getHibernateTemplate().update(companyDept);

						System.out.println("更新部门id:" + companyDept.getId() + " 公司id:" + one.getCompanyId() + " 上级id:" + one.getParentId());
					}

				} catch (Exception ex) {
				}

			}
			// ////systemBranchCompanyDao.flush();
			// 处理岗位
			CompanyDeptTitle companyDeptTitle = null;
			for (Iterator it = titleMap.keySet().iterator(); it.hasNext();) {
				String titleId = (String) it.next();
				one = (CompanyCvTreeNode) titleMap.get(titleId);
				try {
					companyDeptTitle = this.getEntityDao().getHibernateTemplate().get(CompanyDeptTitle.class, StringHelper.parseInteger(titleId, 0));

					System.out.println("岗位id:" + companyDeptTitle.getId() + " 部门id:" + one.getDeptId() + " 上级id:" + StringHelper.parseInteger(one.getParentId(), 0));
					if ((!StringHelper.parseInteger(one.getDeptId(), 0).equals(companyDeptTitle.getDeptId())) || (!StringHelper.parseInteger(one.getParentId(), 0).equals(companyDeptTitle.getParentId()))) {
						companyDeptTitle.setDeptId(StringHelper.parseInteger(one.getDeptId(), 0));
						companyDeptTitle.setParentId(StringHelper.parseInteger(one.getParentId(), 0));
						companyDeptTitle.setModifiedDt(new Date());
						this.getEntityDao().getHibernateTemplate().update(companyDeptTitle);
						System.out.println("更新岗位id:" + companyDeptTitle.getId() + " 部门id:" + one.getDeptId() + " 上级id:" + StringHelper.parseInteger(one.getParentId(), 0));
					}

				} catch (Exception ex) {
				}

			}
			this.getEntityDao().flush();
			// 处理人员（所属岗位）
			CompanyCvTreeNode cvTitleNode = null;

			for (Iterator it = cvMap.keySet().iterator(); it.hasNext();) {
				String cvId = (String) it.next();
				List titleIds = (List) cvMap.get(cvId);

				// 查询已有的
				values = new ArrayList();
				values.add(companyId);
				values.add(StringHelper.parseInteger(cvId, 0));
				List l = this.getEntityDao().getHibernateTemplate().find("from CompanyCv t where t.companyId=? and  t.cvId=?", values.toArray());

				// 删除
				CompanyCv companyCv = null;
				CompanyCv newCompanyCv = null;
				for (int j = 0; l != null && j < l.size(); j++) {
					companyCv = (CompanyCv) l.get(j);
					boolean isDelete = true;
					for (int i = 0; titleIds != null && i < titleIds.size(); i++) {
						cvTitleNode = (CompanyCvTreeNode) titleIds.get(i);
						if (companyCv.getTitleId().equals(StringHelper.parseInteger(cvTitleNode.getTitleId(), 0)))
							isDelete = false;
					}
					if (isDelete) {

						this.getEntityDao().getHibernateTemplate().delete(companyCv);
						System.out.println("删除人员岗位:" + companyCv.getCvId() + "--" + companyCv.getTitleId());
						this.getEntityDao().flush();
					}
				}
				// 新增

				// for(int
				// i=0;titleIds!=null&&titleIds.length>0&&i<titleIds.length;i++){
				for (int i = 0; titleIds != null && i < titleIds.size(); i++) {
					boolean isAdd = true;
					cvTitleNode = (CompanyCvTreeNode) titleIds.get(i);

					for (int j = 0; l != null && j < l.size(); j++) {
						companyCv = (CompanyCv) l.get(j);
						if (companyCv.getTitleId().equals(StringHelper.parseInteger(cvTitleNode.getTitleId(), 0)))
							isAdd = false;
					}
					newCompanyCv = new CompanyCv();
					newCompanyCv.setCompanyId(companyId);
					newCompanyCv.setCvId(StringHelper.parseInteger(cvId, 0));
					newCompanyCv.setDeptId(StringHelper.parseInteger(cvTitleNode.getDeptId(), 0));
					newCompanyCv.setTitleId(StringHelper.parseInteger(cvTitleNode.getTitleId(), 0));
					newCompanyCv.setCreator(onlineUser.getUsername());
					newCompanyCv.setCreateDt(new Date());
					if (isAdd) {
						this.getEntityDao().getHibernateTemplate().save(newCompanyCv);
						System.out.println("新增人员岗位:" + newCompanyCv.getCvId() + "--" + newCompanyCv.getTitleId());
						// 同步cv的部门和岗位
						companyDeptTitle = this.getEntityDao().getHibernateTemplate().get(CompanyDeptTitle.class, StringHelper.parseInteger(cvTitleNode.getTitleId(), 0));
						companyDept = this.getEntityDao().getHibernateTemplate().get(CompanyDept.class, StringHelper.parseInteger(cvTitleNode.getDeptId(), 0));
						Cv cv = this.getEntityDao().getHibernateTemplate().get(Cv.class, StringHelper.parseInteger(cvId, 0));
						if (cv != null) {
							if (companyDeptTitle != null)
								cv.setTitle(companyDeptTitle.getName());
							if (companyDept != null)
								cv.setDept(companyDept.getName());
							this.getEntityDao().getHibernateTemplate().update(cv);
						}
						this.getEntityDao().flush();
					}
				}

			}

		}

	}

	public List getOrgOnly(Integer companyId, Integer deptId) {
		// TODO Auto-generated method stub
		return getOrg(companyId, deptId, false);
	}

	public void deleteCompany(String ids) {
		// TODO Auto-generated method stub

	}

	public void save(Company company) {
		boolean isRepeat = isCompanyRepeat(company);
		if (isRepeat) {
			if (!StringHelper.isEmpty(company.getAbbrName()))
				throw new RepeatRecordException("公司已经存在! 请检查 简称 总机 地址 ");
			// else throw new
			// RepeatRecordException("公司"+company.getName()+"已经存在");
		}
		companyDao.save(company);
	}

	public boolean isCompanyRepeat(Company company) {
		// TODO Auto-generated method stub
		// Object[] os={company.getName(),company.getFullName()};
		StringBuffer sql = new StringBuffer();
		sql.append("from Company t where 1=1 and t.isDelete = 0 ");
		List values = new ArrayList();

		// values.add(" a ( 1<>1 ");
		if (StringUtils.isNotEmpty(company.getAbbrName()) && StringUtils.isEmpty(company.getTel())) {
			sql.append(" and  t.abbrName= ?   ");
			// values.add(company.getAbbrName());
			values.add(company.getAbbrName());

		}
		if (StringUtils.isNotEmpty(company.getAbbrName()) && StringUtils.isNotEmpty(company.getTel())) {
			sql.append(" and  (t.abbrName= ?  or t.tel like ? )  ");
			// values.add(company.getAbbrName());
			values.add(company.getAbbrName());
			values.add("%" + company.getTel() + "%");

		}
		if (StringUtils.isNotEmpty(company.getAddress())) {
			sql.append(" or t.address = ? ");
			values.add(company.getAddress());
		}
		//
		/*
		 * if( !=null && !=null && company.getTel() !=null ){
		 * sql.append(" and  t.abbrName= ? or t.address = ? or t.tel like ?   "
		 * ); //values.add(company.getAbbrName());
		 * values.add(company.getabbrName()); values.add(company.getAddress());
		 * values.add("%"+company.getTel()+"%"); }
		 */
		/*
		 * else if(company.getName() !=null && company.getFullName() ==null ){
		 * sql.append(" and  t.abbrName=? and t.name = ? ");
		 * //values.add(company.getAbbrName());
		 * values.add(company.getAttrName()); values.add(company.getName());
		 * }else if(company.getName() ==null && company.getFullName() !=null){
		 * sql.append(" and  t.abbrName=? and t.fullName = ? ");
		 * //values.add(company.getAbbrName());
		 * values.add(company.getAttrName()); values.add(company.getFullName());
		 * }
		 */
		/*
		 * if (!StringHelper.isEmpty(company.getName())) {
		 * sql.append(" or (t.name=? or t.fullName=? )");
		 * values.add(company.getName()); values.add(company.getName()); }
		 */

		/*
		 * if (!StringHelper.isEmpty(company.getFullName())) {
		 * sql.append(" or (t.name=? or t.fullName=? )");
		 * values.add(company.getFullName()); values.add(company.getFullName());
		 * }
		 */
		// values.add(" ) ");
		//
		List l = this.getEntityDao().getHibernateTemplate().find(sql.toString(), values.toArray());
		if (l != null && l.size() > 0) {
			for (int i = 0; i < l.size(); i++) {
				Company oldCompany = (Company) l.get(i);
				if (company.getId() == null || company.getId().intValue() == 0)
					return true;
				else if (!company.getId().equals(oldCompany.getId()))
					return true;
				// System.out.println("company:company.getId()"+"  old:"+oldCompany.getId());
			}
		}
		return false;
	}

	/**
	 * 检查公司是否受保护客户
	 */
	public boolean isProtect(Integer companyId) {
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();
		// sql.append("select 1 from  customer a,customer_contract b where a.id=b.cust_id and a.company_id=?");
		sql.append("select 1 from  customer b where  b.company_id=?");
		sql.append(" and  ( ");
		sql.append("  exists (select 1 from  customer_contract d where d.begin_d<now() and d.end_d>now() and b.id=d.cust_id ) ");
		sql.append(" or exists (select 1 from  customer_contract c,customer_contract_service_company d where c.id=d.contract_id and c.begin_d<now() and  c.end_d>now() and b.id=d.cust_id ) ");
		sql.append("  ) ");
		values.add(companyId);
		List l = companyDao.getJdbcDao().findByQuery(sql.toString(), values.toArray(), new MapObjectRowMapper());
		if (l != null && l.size() > 0)
			return true;
		return false;
	}

	public Company getByCustId(Integer custId) {
		// TODO Auto-generated method stub
		List l = companyDao.getHibernateTemplate().find("from Customer t where t.id=?", custId);
		Company company = null;
		if (l != null && l.size() > 0) {
			Customer customer = (Customer) l.get(0);
			company = (Company) companyDao.getById(customer.getCompanyId());

		}
		return company;
	}

	public Map getCompanyContext(Integer companyId) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		StringBuffer sql = new StringBuffer();
		List values = new ArrayList();

		sql = new StringBuffer();
		values = new ArrayList();

		sql.append(" select * from ( ");
		sql.append(" select a.abbr_name abbrName,a.location,a.industry  from company a where id=? ");
		sql.append(" ) t ");
		values.add(companyId);
		Map m = new HashMap();
		List l = companyDao.getJdbcDao().findByQuery(sql.toString(), values.toArray(), new MapObjectRowMapper());
		if (l != null && l.size() > 0) {
			Map onem = null;
			onem = (Map) l.get(0);
			m.putAll(onem);
		}

		return m;
	}

	public void saveCompanyCvInfo(Cv cv, CompanyCv companyCv) {
		// TODO Auto-generated method stub
		cvDao.save(cv);
		cvDao.flush();
		companyCv.setCvId(cv.getId());
		companyCv.setCreator(cv.getCreator());
		companyCv.setCreateDt(new Date());
		companyCvDao.save(companyCv);
	}

	public void removeById(Integer id) {
		Company company = (Company) companyDao.getById(id);
		company.setIsDelete(Company.DELETE_FLAG);
		company.setDeleteDt(new Date());
		companyDao.update(company);
		companyDao.flush();
	}

	/*
	 * @Override public void batchUpdate(Company company) {
	 * companyDao.batchUpdate(company);
	 * 
	 * }
	 */
	@Override
	public void importCompanyFromExcel(String path) {
		// TODO Auto-generated method stub
		companyDao.importCompanyFromExcel(path);

	}

	@Override
	public Page findDelPage(CompanyQuery companyQuery) {
		// TODO Auto-generated method stub
		return companyDao.findDelPage(companyQuery);
	}

	@Override
	public void companyMerger(String id, String ids) {
		companyDao.companyMerger(id, ids);

	}

	@Override
	public Page findCompanyMergePage(CompanyQuery companyQuery) {
		// TODO Auto-generated method stub
		return companyDao.findCompanyMergePage(companyQuery);
	}

	@Override
	public Page findSameOfDelCvPage(CompanyQuery companyQuery) {
		// TODO Auto-generated method stub
		return companyDao.findSameOfDelCvPage(companyQuery);
	}

	@Override
	public boolean checkCompanyIntegrity(Integer companyid) {
		// TODO Auto-generated method stub
		return companyDao.checkCompanyIntegrity(companyid);
	}

	@Override
	public void recoverCompany(String ids) {
		// TODO Auto-generated method stub
		companyDao.recoverCompany(ids);
	}
}
